import Vue from "vue";
import VueRouter from "vue-router";
import axios from "axios";
import { Message, MessageBox } from "element-ui";
// 进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store/index";
import util from "@/libs/util.js";
import storage from '@/utils/storage.js';
// 路由数据
import routes from "./routes";
import { dynamicRoutes, frameInRoutes } from "@/router/routes.js";

Vue.use(VueRouter);

// 导出路由 在 main.js 里使用
const router = new VueRouter({
  routes,
});

const noRedirectPaths = dynamicRoutes.map((item) => item.path); //点击顶部模块名，不需要直接重定向的路径

const pageNextAction = (to, from, next) => {
  const headerMenu = store.getters.header;
  const toMenus = to.path.split("/");
  let matchPath = "";
  const keepAlive = store.getters.keepAlive;
  if (keepAlive.includes(to.name)) {
      next();
  } else {
      if (to.meta.level == 0) {
        store.dispatch('admin/menu/switchAsideMenu',to.path).then(() => {
            NProgress.done();
        })
      } else {
          next();
      }
  }
  // console.log("到了这里：",keepAlive.includes(to.name),to.name,to.meta?.level == 0)
  NProgress.done();
};

// 退出登录相关操作
const logoutHanlde = (to, next) => {
  console.log("退出？")
  // const { admin } = useStore();
  // const { account } = admin
  // account.clear()
  store.dispatch('admin/account/clear')
  next({ path: "/login" });
  NProgress.done();
};

// 本系统处理相关逻辑
const selfPlatformHandle = (to, from, next) => {
  const token = util.cookies.get("token");
  if (token && token !== "undefined") {
      // 菜单权限业务逻辑
      const remoteMenu = store.getters.remoteMenu > 0?store.getters.remoteMenu:storage.getStorage('menuTree');
      // console.log("倒数第二部：",remoteMenu,storage.getStorage('menuTree'),to,from,next)
      if (remoteMenu && remoteMenu.length === 0) {
        MessageBox.alert(
              "您的账号还未被授权，请联系企业管理员授权使用！",
              "提示",
              {
                  confirmButtonText: "确定",
                  type: "warning",
                  callback: () => {
                      logoutHanlde(to, next);
                  }
              }
          );
      } else if (remoteMenu && remoteMenu.length !== 0) {
          pageNextAction(to, from, next);
      } else {
        store.dispatch('admin/menu/getRemoteMenu').then(res=>{
          if (res.length === 0) {
            store.dispatch('admin/account/logout')
              NProgress.done();
              if (to.path !== "/login") {
                  ElMessageBox.alert(
                      "您的账号还未被授权，请联系企业管理员授权使用！",
                      "提示",
                      {
                          confirmButtonText: "确定",
                          type: "warning"
                      }
                  );
              }
          } else {
              pageNextAction(to, from, next);
          }
        }).catch(e => {
            // console.log(e);
            logoutHanlde(to, next);
        })
      }
  } else {
      logoutHanlde(to, next);
  }
};

/**
* 路由拦截
* 权限验证
*/
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if(!to.name){
      storage.removeStorage('breadList')
      storage.removeStorage('asideActiveIndex')
      return next({ path: "/404" });
  }
  //未登录
  if (!util.cookies.get('token') && to.path !== "/login") {
      // if(to.path == '/forgetpass' || to.path.indexOf('h5') != -1){
      //     return next();
      // }else{
          return next({ path: "/login" });
      // }
  };
  //已登录
  if (util.cookies.get('token') && to.path == "/login") return next({ path: "/" });
  //重新加载动态路由
  // console.log("倒数第三部：",to,to.matched.some(r => r.meta.auth))
  if (to.matched.some(r => r.meta.auth)) {
      selfPlatformHandle(to, from, next);
  } else {
      next();
      NProgress.done();
  }
});

router.afterEach(to => {
  // const { admin } = useStore();
  // const { page } = admin
  // NProgress.done();
  // page.open(to)
  // util.title(to.meta.title);
});

router.onError(error => {
  console.log("router.onError,error=", error);
  const jsPattern = /Loading chunk (\S)+ failed/g;
  const cssPattern = /Loading CSS chunk (\S)+ failed/g;
  const isChunkLoadFailed = error.message.match(jsPattern || cssPattern);
  const targetPath = router.currentRoute.value.fullPath;
  if (isChunkLoadFailed) {
      console.log("router.onError,targetPath=", targetPath);
      storage.setStorage("targetPath", targetPath);
      window.location.reload();
  }
});

// router.isReady().then(() => {
//   console.log("router.onError,onReady=", 1);
//   const targetPath = storage.getStorage("targetPath");
//   const tryReload = storage.getStorage("tryReload");
//   if (targetPath) {
//       console.log("router.onError,onReady=", 1, targetPath);
//       storage.removeStorage("targetPath");
//       if (!tryReload) {
//           console.log("router.onError,onReady=", 1, tryReload);
//           router.push(targetPath);
//           storage.setStorage("tryReload", true);
//       } else {
//           storage.removeStorage("tryReload");
//       }
//   }
// });

router.afterEach((to, from) => {
  NProgress.done()
})

export default router;
